﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Web.Mvc;
using System.Web.Security;
using L.Manage;
using System.Net;

namespace System.Web.Mvc
{
    /// <summary>
    /// 用户身份认证属性，如果为指定角色、权限，将只对用户进行登录验证
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class LAuthorizeAttribute : FilterAttribute, IAuthorizationFilter
    {
        /// <summary>
        /// 需要进行角色验证，多个角色用
        /// </summary>
        public string RequireRole { get; set; }

        /// <summary>
        /// 需要进行权限验证
        /// </summary>
        public string RequirePermission { get; set; }

        /// <summary>
        /// 需要行进权限验证的模块
        /// </summary>
        public string RequireModule { get; set; }

        #region IAuthorizationFilter 成员

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            //执行用户登录验证
            if (Authentication.Context == null || Authentication.Context.CurrentUser == null)
            {
               // filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                filterContext.Result  = new HttpUnauthorizedResult();
                return;
            }

            //执行用户角色验证
            if (!string.IsNullOrWhiteSpace(RequireRole))
            {
                if (!Authentication.Context.IsInRole(RequireRole))
                {
                    throw new Exception("当前登录用户不属于角色：" + RequireRole);
                }
            }

            //执行用户权限验证。必须要满足RequireModule，RequireModule都不为空。
            if (!string.IsNullOrWhiteSpace(RequireModule) && !string.IsNullOrWhiteSpace(RequireModule))
            {
                if (!Authentication.Context.HasPermission(RequireModule, RequirePermission))
                {
                    throw new Exception(string.Format("当前登录用户不具备对 {0} 的 {1} 权限", RequireModule, RequirePermission));
                }
            }
        }

        #endregion
    }
}